<template>
    <div id="addTrends">
        <head-tip @tomove="toSomeUrl" title='发布文章' :isArt=true>
            <div class="head-right">
                <span @click="sendArt" class="link icon-only" style="font-size: 18px; margin-right: 10px;color: #333;">发布</span>
            </div>
        </head-tip>
        <div class="publish-article-title">
            <input type="text" v-model="articleajax.ctitle" placeholder="文章标题">
        </div>
        <div>
            <div class="quill-editor-example">
                <div id="editorElem" style="text-align:left"></div>
                <!-- <quill-editor 
                            placeholder="写点什么吧..."
                            v-model="content"
                            ref="newEditor"
                            :options="editorOption">
                </quill-editor> -->
            </div>
            <div v-if="tochoose" @click="beforeCh" class="chooseCard">请选择要发布的名片（已选{{this.$store.state.publicCard.length}}）</div>
        </div>
    </div>
</template>

<script>
import {tosendArt,getArtDetail} from '../../js/dataServe.js'

// import { quillEditor } from 'vue-quill-editor'
import E from 'wangeditor'

import headTip from '@/components/common/head'

// import 'quill/dist/quill.core.css'
// import 'quill/dist/quill.snow.css'
// import 'quill/dist/quill.bubble.css'
export default {

    data(){
        return {
            issending:false,
            chooseArr:this.$store.state.publicCard,//名片id数值
            articleajax:{
                ctitle:'',
                ccontent:'',
                ccardid:this.$route.query.id,
                itype:0,
            },
            files:[],//文件组
            tochoose:false,
            isBack:false,//跳转方式
            content: ``,
            // editorOption: {
            //     modules: {
            //         toolbar:{
            //             container: [
            //                             [{ 'size': ['small', false, 'large'] }],
            //                             ['bold', 'italic'],
            //                             ['image'],
            //                             [{ 'align': [] }],
            //                             [{ 'color': [] }]
            //                         ]
            //         },
                    
            //         history: {
            //             delay: 1000,
            //             maxStack: 50,
            //             userOnly: false
            //         }
            //     }
            // }
        }
    },
    activated () {
        if(this.$route.meta.isActive == true){
            document.querySelector('.w-e-text').innerHTML = ''
            let id = this.$route.query.id;
            let artid = this.$route.query.artid;
            if(artid){
                let responseData = getArtDetail(artid);
                let self = this;
                responseData.then((res)=>{
                                            if(res.result==1){
                                                self.articleajax.ctitle = res.data.ctitle;
                                                self.articleajax.ccontent=document.querySelector('.w-e-text').innerHTML = res.data.ccontent;
                                                self.articleajax.ccardid = res.data.ccardid;
                                            }else{
                                                
                                            }
                                        })
            }
            if(id > 0 || artid>0){
                this.tochoose = false
            }else{
                this.tochoose = true
            }
            this.articleajax.ctitle = ''
        }
        this.chooseArr = this.$store.state.publicCard
    },
    methods:{
        dataURLtoFile(dataurl, filename) {
            var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new File([u8arr], filename, {type:mime});
        },
        sendArt(){
            // var imagenames=[]
            if(!this.issending){
                this.issending = true;
                let artid = this.$route.query.artid;

                if(!this.articleajax.ctitle){
                    alert('请输入标题')
                    this.issending = false
                    return false;
                }
                if(!this.content && this.content!=''){
                    alert('请输入内容')
                    this.issending = false
                    return false
                }
                if(this.tochoose && this.chooseArr.length<=0){
                    alert('请输选择要发布的名片')
                    this.issending = false
                    return false
                }
                let loading = this.$loading({
                                            lock: false,
                                            spinner: 'el-icon-loading',
                                            background: 'rgba(0, 0, 0, 0)',
                                            text:'提交中...',
                                            customClass:'changeColor',
                                        });

                if(!this.articleajax.ccardid>0){
                    // console.log(this.chooseArr)
                    this.articleajax.ccardid = this.chooseArr.join(',')
                    console.log(this.articleajax.ccardid)
                }
                let self = this;

                document.querySelectorAll('.quill-editor-example img').forEach(function(v,k){
                    if(v.src.indexOf('attach') ==-1){               
                        var canvas = document.createElement('canvas');
                        var context = canvas.getContext('2d');
                        canvas.width = v.width;
                        canvas.height = v.height;
                        // 清除画布
                        context.clearRect(0, 0, v.width, v.height);
                        // 图片压缩
                        context.drawImage(v, 0, 0, v.width, v.height);
                        var dataURL=canvas.toDataURL('image/jpeg',1);
                        

                        let fv = self.dataURLtoFile(dataURL);
                        let newfile = new File([fv], new Date().getTime()+".jpg",{type:"image/jpeg"});
                        self.files.push(newfile)
                        // let src = window.URL.createObjectURL(newfile);
                        v.setAttribute('src',newfile.name)
                        v.setAttribute('data-name',newfile.name)

                    }
                })
                this.articleajax.ccontent = document.querySelector('.w-e-text').innerHTML
    

                var  formData=new FormData();
                for(let i in this.articleajax){
                    formData.append(i,this.articleajax[i]);
                }
                this.files.forEach(function(v){
                    if(v){
                        formData.append('files',v)
                    }
                })
                if(artid){
                    formData.append('id',artid)
                }
                let responseData = tosendArt(formData);
                responseData.then((res)=>{
                                            if(res.result==1){
                                                if(artid){
                                                    self.$message({
                                                        duration: 2000,
                                                        message: '编辑成功',
                                                        type: 'success'
                                                    })
                                                }else{
                                                    self.$message({
                                                        duration: 2000,
                                                        message: '发布成功',
                                                        type: 'success'
                                                    })
                                                }

                                                setTimeout(function(){
                                                    if(!self.tochoose){
                                                        self.$router.back(-1)
                                                    }else{
                                                        self.$router.push({path:"/mine/myArtical"})
                                                    }
                                                    self.issending = false;
                                                },1000)
                                            }else{
                                                self.$message({
                                                    duration: 2000,
                                                    message: '发布失败',
                                                    type: 'error'
                                                })
                                            }
                                            loading.close()
                                            // Indicator.close();
                                        })
            }
            
        },
        // //选择名片前
        beforeCh(){
            this.$router.push({path:"/mine/commonCard",query:{type:"article"}})
        },
        toSomeUrl(){
            if(!this.tochoose){
                this.$router.back(-1)
            }else{
                this.$router.push({path:"/mine/myArtical"})
            }
        }
    },  
    components:{
        // quillEditor,
        headTip,
        // quillEditor
    },
    created(){
    },
    mounted(){
        var editor = new E('#editorElem')
        editor.customConfig.onchange = (html) => {
          this.editorContent = html
        }
        
        editor.customConfig.menus = [          //菜单配置
            'justify',  // 对齐方式
            'bold',
            'italic',
            'underline',
            'image',  // 插入图片
            'foreColor',  // 文字颜色
            'undo',  // 撤销
        ]
        editor.customConfig.uploadImgShowBase64 = true 
        editor.create()
        let id = this.$route.query.id;
        let artid = this.$route.query.artid;
        // console.log(id)
        if(id > 0 || artid){
            this.tochoose = false
        }else{
            this.tochoose = true
        }

        //获取文章详情
        if(artid){
            let responseData = getArtDetail(artid);
            let self = this;
            responseData.then((res)=>{
                                        if(res.result==1){
                                            self.articleajax.ctitle = res.data.ctitle;
                                            self.articleajax.ccontent=document.querySelector('.w-e-text').innerHTML = res.data.ccontent;
                                            self.articleajax.ccardid = res.data.ccardid;
                                        }else{
                                            
                                        }
                                    })
        }

    },
    beforeRouteEnter(to,from,next){
        if(from.name != 'commonCard'){
            to.meta.isActive = true;
        }
        next();
    },
    beforeRouteLeave(to,from,next){
        from.meta.isActive = false;
        next();
    }
}
</script>
<style>
    body,html{
        height: auto !important;
    }
    .content img{
        max-width: 100%;
    }
</style>

<style scoped>
.quill-editor div{
   border:none !important;
}
.quill-editor{
    position: absolute;
    width: 100%;
    top:6rem;
    bottom:3rem;
    background: #ffffff;
}
.publish-article-title{
    padding: .6rem;
    background: #fff;
    // margin-bottom: 10px;
    margin-top:3rem;
}
.publish-article-title input {
    border: none;
    font-size: 14px;
    height: 20px;
    line-height: 20px;
    padding: 5px;
    color: #666;
    font-family: "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", "宋体", Arial, Verdana, sans-serif;
    width: 100%;
    background: #fff;
    outline: none;
    border-radius: none;
    box-sizing: border-box;
}
.chooseCard{
    color:red;
    display: block;
    width: 100%;
    height: 3rem;
    line-height: 3rem;
    padding: 0 1rem;
    background: #efefef;
    box-sizing:border-box;
    position: fixed;
    bottom: 0;
    left: 0;
    z-index:10000;
}
.chooseitems{
    max-height:6rem;
    overflow:auto;
}
#head {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    height: 3rem;
    line-height: 3rem;
    font-size: 1.2rem;
    width: 100%;
    background:#eee;
    color: #303133;
    position: fixed;
    top: 0;
    z-index: 10;
}
#head p{
    color:#ffffff;
}
#head .isline{
    position: absolute;
    bottom: 0;
    display: block;
    width: 100%;
    height: 50%;
    border-bottom: 1px solid #DCDFE6;
    box-sizing: border-box;
    box-shadow: 0rem 0.1rem 0.2rem #EBEEF5;
}
#head .toback{
    position: absolute;
    color: #ffffff;
    top: 0;
    bottom: 0;
    left: 0;
    margin: auto;
    line-height: 3rem;
    font-size: 2rem;
    padding-left: 0.5rem;
    z-index: 100;
}
.addTrend{
    position: absolute;
    right: 1rem;
    top: 0;
}
.addTrend i{
    display: block;
    line-height: 3rem;
    font-size: 1.5rem;
    color: #F56C6C;
}
</style>
